<?php

namespace App\Services;

use App\Ad\Postback\PostbackService;
use App\Models\Orders;
use App\Models\OrdersCallClient;

class OrdersCallClientService extends ServiceBase
{
    public function addCall($order, $call_money = 0)
    {
        if ($call_money === 0) {
            $call_money = $order->money;
        }

        $call = OrdersCallClient::where('order_id', $order->id)->first();
        if (!$call) {
            $call              = new OrdersCallClient;
            $call->create_time = time();
            $call->user_id     = $order->user_id;
            $call->order_id    = $order->id;
            $call->call_amount = $call_money;
            $call->save();
        }
    }

    public function getAndUpdateCallInfo($user_id)
    {
        $list  = [];
        $now   = time();
        $ctime = $now - 86400 * 3;
        $calls = OrdersCallClient::whereRaw("create_time>={$ctime} AND create_time<{$now} AND user_id={$user_id} AND is_call=0")->get()->keyBy('order_id');
        if ($calls->isEmpty()) {
            return $list;
        }

        $ids    = array_column($calls->toArray(), 'order_id');
        $orders = Orders::whereIn('id', $ids)->get();
        foreach ($orders as $val) {
            $call            = $calls[$val->id];
            $call->is_call   = 1;
            $call->call_time = $now;
            $call->save();

            PostbackService::getInstance()->updateSdkPayStatus($val);

            $list[] = [
                'user_id'        => $val->user_id,
                'create_time'    => $val->create_time,
                'trade_no'       => $val->trade_no,
                'game_trade_no'  => $val->game_trade_no,
                'channel_openid' => $val->channel_openid,
                'amount'         => $call->call_amount,
                'server_id'      => $val->server_id,
                'goods_id'       => $val->goods_id,
                'goods_name'     => $val->goods_name,
            ];
        }

        return $list;
    }
}
